<!--
 *Author：jxx
 *Contact：283591387@qq.com
 *仓库详细信息页面
 -->
<template>
    <div class="warehouse-detail-container">
        <!-- 基础信息区域 -->
        <div class="info-section">
            <div class="section-title">基础信息</div>
            <div class="form-content">
                <el-form :model="formData" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="仓库编号" required>
                                <div style="display: flex; gap: 8px;">
                                    <el-input v-model="formData.WarehouseCode" placeholder="自动获取系统编号"
                                        :readonly="!route.query.id" style="flex: 1">
                                    </el-input>
                                    <el-button v-if="!route.query.id" type="primary" size="default"
                                        @click="regenerateWarehouseCode" :loading="regenerating">
                                        重新生成
                                    </el-button>
                                </div>
                                <div v-if="!route.query.id" style="font-size: 12px; color: #909399; margin-top: 4px;">
                                    格式：CK + 日期(YYYYMMDD) + 序号(001)，如：CK20241031001
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="仓库名称" required>
                                <el-input v-model="formData.WarehouseName" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="仓库容量/m³">
                                <el-input v-model="formData.Capacity" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="库管部门">
                                <el-cascader v-model="formData.deptId" :options="departmentOptions" :props="{
                                    checkStrictly: true,
                                    value: 'value',
                                    label: 'label',
                                    children: 'children',
                                    emitPath: false,
                                    expandTrigger: 'hover',
                                    multiple: false
                                }" placeholder="请选择部门" clearable filterable :show-all-levels="true"
                                    @change="handleDeptChange" style="width: 100%">
                                    <template #default="{ node, data }">
                                        <span>{{ data.label }}</span>
                                    </template>
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="仓库主管">
                                <el-select v-model="formData.userId" placeholder="请选择仓库主管" filterable clearable
                                    @change="handleUserChange">
                                    <el-option v-for="item in userOptions" :key="item.value" :label="item.label"
                                        :value="item.value">
                                        <span style="float: left">{{ item.label }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话">
                                <el-input v-model="formData.phone" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="仓库地址">
                                <el-input v-model="formData.Warehouseaddr" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="排序">
                                <el-input v-model="formData.orderNo" type="number" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="仓库状态">
                                <el-radio-group v-model="formData.status">
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input v-model="formData.WarehouseDesc" type="textarea" :rows="4" placeholder="请输入">
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>

        <!-- 库位信息区域 -->
        <div class="location-section">
            <div class="section-title">库位信息</div>

            <!-- 用户提示信息 -->
            <div class="location-tips">
                <el-alert v-if="selectedLocations.length > 0"
                    :title="`已选中 ${selectedLocations.length} 个库位，保存时将自动关联到当前仓库【${formData.WarehouseName || '新仓库'}】`"
                    type="success" :closable="false" show-icon>
                </el-alert>
                <el-alert v-else title="请在下方表格中勾选需要关联到当前仓库的库位，然后点击保存按钮" type="warning" :closable="false" show-icon>
                    <template #default>
                        <div style="margin-top: 8px;">
                            <p><strong>💡 操作提示：</strong></p>
                            <p>1. 在表格左侧勾选框中选择需要关联的库位</p>
                            <p>2. 可以选择单个或多个库位</p>
                            <p>3. 选择完成后点击页面底部的"保存"按钮</p>
                        </div>
                    </template>
                </el-alert>
            </div>

            <div class="table-actions">
                <div class="action-group">
                    <el-button type="success" size="small" @click="addLocation">新增</el-button>
                    <el-button type="danger" size="small" @click="deleteLocation">删除</el-button>
                    <el-button type="primary" size="small" @click="importLocation">导入</el-button>
                    <el-button type="warning" size="small" @click="exportLocation">导出</el-button>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="selection-group">
                    <el-tag :type="selectedLocations.length > 0 ? 'success' : 'info'" size="large"
                        style="margin-right: 10px;">
                        已选中: {{ selectedLocations.length }}/{{ locationData.length }}
                    </el-tag>
                    <el-button type="primary" size="small" @click="selectAllLocations"
                        :disabled="locationData.length === 0">
                        全选库位
                    </el-button>
                    <el-button type="default" size="small" @click="clearAllSelections"
                        :disabled="selectedLocations.length === 0">
                        清空选择
                    </el-button>
                    <el-button type="info" size="small" @click="debugSelection">
                        🔍 调试选择
                    </el-button>
                    <el-button type="warning" size="small" @click="debugLocationIds">
                        🔧 调试库位ID
                    </el-button>
                    <el-button type="success" size="small" @click="batchUpdateWarehouseId"
                        :disabled="selectedLocations.length === 0 || !formData.Id">
                        🔗 批量关联到当前仓库
                    </el-button>
                </div>
            </div>
            <div class="table-content">
                <el-table :data="locationData" style="width: 100%" @selection-change="handleSelectionChange"
                    ref="locationTable">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="index" label="序号" width="70"></el-table-column>
                    <el-table-column prop="code" label="库位编号" width="120"></el-table-column>
                    <el-table-column prop="name" label="库位名称" width="120"></el-table-column>
                    <el-table-column prop="capacity" label="库位容量/m³" width="120"></el-table-column>
                    <el-table-column prop="warehouseName" label="所属仓库" width="120"></el-table-column>
                    <el-table-column prop="manager" label="库位主管" width="120"></el-table-column>
                    <el-table-column prop="order" label="排序" width="70"></el-table-column>
                    <el-table-column prop="status" label="库位状态" width="100">
                        <template #default="scope">
                            <span>{{ scope.row.status === 1 ? '启用' : '停用' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注"></el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="editLocation(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="deleteLocationItem(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination">
                <span>总 {{ totalLocations }} 条</span>
                <el-pagination background layout="prev, pager, next" :total="totalLocations" :current-page="currentPage"
                    :page-size="pageSize" @current-change="handleCurrentChange">
                </el-pagination>
                <div class="page-size-selector">
                    <el-input v-model="jumpToPage" style="width: 50px"></el-input>
                    <el-select v-model="pageSize" style="width: 100px" @change="handlePageSizeChange">
                        <el-option :value="10" label="10条/页"></el-option>
                        <el-option :value="20" label="20条/页"></el-option>
                        <el-option :value="50" label="50条/页"></el-option>
                        <el-option :value="100" label="100条/页"></el-option>
                    </el-select>
                </div>
            </div>
        </div>

        <div class="form-actions">
            <el-button type="primary" @click="saveWarehouse">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 表单数据 - 根据数据库表字段进行绑定
const formData = reactive({
    Id: 0,                // 主键ID
    WarehouseCode: '',    // 仓库编号
    WarehouseName: '',    // 仓库名称
    Capacity: '',         // 仓库容量
    Warehouseaddr: '',    // 仓库地址
    deptId: '',           // 部门Id - 使用单个值，不是数组，与后端字段保持一致
    userId: 0,            // 仓库主管 - 使用数字类型，与数据库一致
    status: 1,            // 状态
    WarehouseDesc: '',    // 备注
    IsDel: 0,             // 删除标识
    Creator: '',          // 创建人
    CreateDate: '',       // 创建时间
    Modifier: '',         // 修改人
    ModifyDate: '',       // 修改时间
    CreateID: 0,          // 创建人id
    ModifyID: 0,          // 修改人id
    phone: '',            // 联系电话 (自定义字段，非数据库字段)
    orderNo: 0            // 排序 (自定义字段，非数据库字段)
});

// 部门选项
const departmentOptions = ref([]);
// 部门ID到名称的映射表，用于显示部门名称
const departmentMap = ref({});

// 用户选项
const userOptions = ref([]);

// 库位数据
const locationData = ref([]);

// 分页和查询参数
const totalLocations = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const jumpToPage = ref(1);

// API请求参数
const queryParams = reactive({
    page: 0,
    rows: 10,
    total: 0,
    tableName: "storagelocationmodel",
    sort: "",
    order: "",
    wheres: "",
    value: "",
    filter: []
});

// 选中的库位
const selectedLocations = ref([]);

// 表格引用
const locationTable = ref(null);

// 重新生成仓库编号的加载状态
const regenerating = ref(false);

// 生成仓库编号
const generateWarehouseCode = async () => {
    try {
        // 获取当前日期，格式为 YYYYMMDD
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const dateStr = `${year}${month}${day}`;

        console.log('🗓️ 当前日期:', dateStr);

        // 查询当天已有的仓库编号数量
        const todayPrefix = `CK${dateStr}`;
        console.log('🔍 查询前缀:', todayPrefix);

        // 调用API查询当天的仓库编号
        const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
            page: 0,
            rows: 1000,
            sort: "Id desc", // 按ID降序，获取最新的编号
            order: "",
            wheres: `WarehouseCode LIKE '${todayPrefix}%'`, // 查询当天的编号
            tableName: "warehousemodel",
            filter: []
        });

        let nextNumber = 1; // 默认从001开始

        if (response && response.rows && response.rows.length > 0) {
            console.log('📋 找到当天已有仓库编号:', response.rows.length, '个');

            // 提取所有当天的编号，找出最大序号
            const todayCodes = response.rows
                .map(item => item.WarehouseCode || item.warehouseCode || '')
                .filter(code => code.startsWith(todayPrefix))
                .map(code => {
                    // 提取编号部分，如 CK20241031001 -> 001
                    const numberPart = code.substring(todayPrefix.length);
                    return parseInt(numberPart) || 0;
                })
                .filter(num => !isNaN(num));

            console.log('📊 当天已有编号:', todayCodes);

            if (todayCodes.length > 0) {
                const maxNumber = Math.max(...todayCodes);
                nextNumber = maxNumber + 1;
                console.log('🔢 最大编号:', maxNumber, '下一个编号:', nextNumber);
            }
        } else {
            console.log('📋 当天还没有仓库编号，从001开始');
        }

        // 生成完整的仓库编号：CK + 日期 + 3位序号
        const warehouseCode = `${todayPrefix}${String(nextNumber).padStart(3, '0')}`;

        console.log('✅ 生成的仓库编号:', warehouseCode);
        return warehouseCode;

    } catch (error) {
        console.error('❌ 生成仓库编号失败:', error);

        // 如果API调用失败，使用备用方案
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const timeStr = String(today.getHours()).padStart(2, '0') + String(today.getMinutes()).padStart(2, '0');

        const fallbackCode = `CK${year}${month}${day}${timeStr}`;
        console.log('🔄 使用备用编号:', fallbackCode);
        return fallbackCode;
    }
};

// 重新生成仓库编号
const regenerateWarehouseCode = async () => {
    try {
        regenerating.value = true;
        console.log('🔄 手动重新生成仓库编号...');

        const newCode = await generateWarehouseCode();
        formData.WarehouseCode = newCode;

        console.log('✅ 重新生成完成:', newCode);
        proxy.$message.success(`已重新生成仓库编号: ${newCode}`);

    } catch (error) {
        console.error('❌ 重新生成仓库编号失败:', error);
        proxy.$message.error('重新生成仓库编号失败: ' + (error.message || '未知错误'));
    } finally {
        regenerating.value = false;
    }
};

// 加载数据
onMounted(async () => {
    // 获取路由参数
    const id = route.query.id;
    if (id) {
        await loadWarehouseData(id);
    } else {
        // 新增模式下自动生成仓库编号
        console.log('🆕 新增模式，自动生成仓库编号...');
        const autoCode = await generateWarehouseCode();
        formData.WarehouseCode = autoCode;
        console.log('📝 已设置仓库编号:', formData.WarehouseCode);
    }

    // 加载部门和用户数据
    await loadDepartments();
    await loadUsers();

    // 加载库位数据
    await loadStorageLocations();
});

// 加载仓库数据
const loadWarehouseData = async (id) => {
    try {
        // 调用API获取仓库数据
        const response = await proxy.http.get(`/api/warehousemodel/getDetailOnlyId?id=${id}`);
        if (response && response.status) {
            // 将API返回的数据映射到表单
            Object.assign(formData, response.data);

            // 确保数字类型字段正确
            formData.Capacity = formData.Capacity || '';
            formData.Id = formData.Id || 0;
            // 确保userId是数字类型
            formData.userId = parseInt(formData.userId || 0);
            formData.deptId = formData.deptId || '';
            formData.status = formData.status === undefined ? 1 : formData.status;
            formData.IsDel = formData.IsDel === undefined ? 0 : formData.IsDel;
            formData.CreateID = formData.CreateID || 0;
            formData.ModifyID = formData.ModifyID || 0;

            console.log('加载后的userId:', formData.userId, '类型:', typeof formData.userId);

            // 加载部门名称
            if (formData.deptId) {
                // 如果部门映射表中没有这个部门ID，需要先加载部门数据
                if (!departmentMap.value[formData.deptId]) {
                    await loadDepartments();
                }
                console.log('加载的部门ID:', formData.deptId);
                console.log('对应的部门名称:', getDepartmentName(formData.deptId));
            }

            console.log('加载仓库数据成功:', formData);
        } else {
            proxy.$message.error(response.message || '加载仓库数据失败');
        }
    } catch (error) {
        console.error('加载仓库数据失败', error);
        proxy.$message.error('加载仓库数据失败');
    }
};

// 加载部门数据
const loadDepartments = async () => {
    try {
        // 调用API获取部门数据 - 使用图片中显示的API路径
        const response = await proxy.http.post('/api/Sys_Department/GetPageData', {
            page: 0,
            rows: 1000, // 获取足够多的数据
            sort: "",
            order: "",
            wheres: "",
            tableName: "Sys_Department",
            filter: []
        });

        if (response && response.rows) {
            console.log('部门数据原始响应:', response);

            // 处理部门数据为级联选择器格式
            // 根据API返回的实际字段结构进行映射
            const deptData = response.rows.map(item => {
                const deptId = item.departmentId || item.DepartmentId || item.id;
                const deptName = item.departmentName || item.DepartmentName || item.name;

                // 构建部门ID到名称的映射
                departmentMap.value[deptId] = deptName;

                return {
                    value: deptId,
                    label: deptName,
                    parentId: item.parentId || item.ParentId || item.pid || "0",
                    departmentCode: item.departmentCode || item.DepartmentCode || item.code,
                    departmentType: item.departmentType || item.DepartmentType || item.type,
                    enable: item.enable || item.Enable || 1,
                    remark: item.remark || item.Remark || ""
                };
            });

            console.log("原始部门数据:", deptData);

            // 转换为树形结构
            // 确保使用正确的parentId关系构建树
            departmentOptions.value = buildDepartmentTree(deptData);
            console.log('转换后的部门数据:', departmentOptions.value);
        } else {
            // 如果API调用失败，使用默认数据
            departmentOptions.value = [
                {
                    value: 1,
                    label: '总部',
                    children: [
                        { value: 11, label: '采购部' },
                        { value: 12, label: '销售部' }
                    ]
                },
                {
                    value: 2,
                    label: '分公司',
                    children: [
                        { value: 21, label: '仓储部' },
                        { value: 22, label: '物流部' }
                    ]
                }
            ];
            console.log('使用默认部门数据');
        }
    } catch (error) {
        console.error('加载部门数据失败', error);
        proxy.$message.error('加载部门数据失败');
    }
};

// 加载用户数据
const loadUsers = async () => {
    try {
        // 调用API获取用户数据 - 使用正确的API路径
        const response = await proxy.http.post('/api/User/GetPageData', {
            page: 0,
            rows: 1000, // 获取足够多的数据
            sort: "",
            order: "",
            wheres: "",
            tableName: "Sys_User",
            filter: []
        });

        if (response && response.rows) {
            console.log('用户数据原始响应:', response);

            // 将API返回的用户数据转换为下拉选项格式
            userOptions.value = (response.rows || []).map(item => {
                // 根据API响应中的实际字段名称进行映射 - 确保使用数字类型的ID
                const userId = parseInt(item.User_Id || 0);

                // 根据API响应使用UserTrueName字段作为显示名称
                const userName = item.UserTrueName || '';

                console.log(`用户ID: ${userId}, 用户名: ${userName}, 原始数据:`, item);

                return {
                    value: userId,  // 确保使用数字类型
                    label: userName
                };
            });

            console.log('转换后的用户选项:', userOptions.value);
        } else {
            // 如果API调用失败，使用默认数据
            userOptions.value = [
                { value: 1, label: '延陵美' },
                { value: 2, label: '潭雨柏' },
                { value: 3, label: '宗政欣欣' },
                { value: 4, label: '马雅柔' }
            ];
            console.log('使用默认用户数据');
        }
    } catch (error) {
        console.error('加载用户数据失败', error);
        proxy.$message.error('加载用户数据失败');
    }
};

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedLocations.value = selection;
    console.log('🔄 库位选择发生变化，当前选中数量:', selection.length);

    // 详细记录每个选中库位的信息，特别是ID字段
    console.log('📋 选中的库位详情:');
    selection.forEach((item, index) => {
        const locationId = item.id || item.originalData?.id || item.locationId || item.Id || item.originalData?.Id;
        console.log(`  ${index + 1}. 库位信息:`, {
            code: item.code,
            name: item.name,
            id: item.id,
            extractedId: locationId,
            warehouseId: item.warehouseId,
            hasOriginalData: !!item.originalData,
            originalDataKeys: item.originalData ? Object.keys(item.originalData) : '无'
        });

        if (!locationId || isNaN(parseInt(locationId))) {
            console.warn(`⚠️ 库位 ${item.code || '未知'} 的ID无效:`, locationId);
        }
    });

    console.log('📊 选择统计:');
    console.log(`  - 总选中数量: ${selection.length}`);
    const validIds = selection.filter(item => {
        const id = item.id || item.originalData?.id || item.locationId || item.Id || item.originalData?.Id;
        return id && !isNaN(parseInt(id));
    });
    console.log(`  - 有效ID数量: ${validIds.length}`);

    if (validIds.length !== selection.length) {
        console.warn(`⚠️ 存在${selection.length - validIds.length}个库位的ID无效，可能影响后续操作`);
    }
};

// 调试选择功能
const debugSelection = () => {
    console.log('🔍 === 库位选择调试信息 ===');
    console.log('📊 当前选中库位数量:', selectedLocations.value.length);
    console.log('📋 选中库位详情:', selectedLocations.value);
    console.log('🗃️ 总库位数量:', locationData.value.length);
    console.log('📄 库位数据前3项:', locationData.value.slice(0, 3));
    console.log('🎮 表格引用是否存在:', !!locationTable.value);
    console.log('🔗 表格引用详情:', locationTable.value);

    // 显示调试信息对话框
    proxy.$alert(`
        选中库位数量: ${selectedLocations.value.length}
        总库位数量: ${locationData.value.length}
        表格引用: ${locationTable.value ? '✅ 正常' : '❌ 异常'}
        
        ${selectedLocations.value.length > 0 ?
            '已选中库位:\n' + selectedLocations.value.map(item => `• ${item.code} - ${item.name}`).join('\n')
            : '⚠️ 当前没有选中任何库位\n请在表格左侧复选框中勾选库位'}
    `, '库位选择调试信息', {
        confirmButtonText: '知道了'
    }).catch(() => {
        // 忽略用户关闭对话框的操作
    });
};

// 调试库位ID功能
const debugLocationIds = () => {
    console.log('🔧 === 库位ID调试信息 ===');

    // 检查所有库位数据的ID字段
    console.log('📊 所有库位数据ID检查:');
    const idAnalysis = {
        totalLocations: locationData.value.length,
        validIds: 0,
        invalidIds: 0,
        missingIds: 0,
        details: []
    };

    locationData.value.forEach((location, index) => {
        const idInfo = {
            index: index + 1,
            code: location.code,
            name: location.name,
            id: location.id,
            idType: typeof location.id,
            isValidId: location.id && !isNaN(parseInt(location.id)),
            originalDataId: location.originalData?.id,
            allIdFields: {
                id: location.id,
                Id: location.Id,
                locationId: location.locationId,
                originalId: location.originalData?.id,
                originalLocationId: location.originalData?.locationId
            }
        };

        if (idInfo.isValidId) {
            idAnalysis.validIds++;
        } else if (location.id === undefined || location.id === null) {
            idAnalysis.missingIds++;
        } else {
            idAnalysis.invalidIds++;
        }

        idAnalysis.details.push(idInfo);
        console.log(`库位${index + 1}:`, idInfo);
    });

    console.log('📈 ID分析统计:', idAnalysis);

    // 检查选中库位的ID
    if (selectedLocations.value.length > 0) {
        console.log('📋 选中库位ID检查:');
        const selectedIds = selectedLocations.value.map((location, index) => {
            const possibleIds = [
                location.id,
                location.originalData?.id,
                location.locationId,
                location.Id,
                location.originalData?.Id,
                location.originalData?.locationId
            ];

            const validId = possibleIds.find(id => id && !isNaN(parseInt(id)));
            const result = {
                index: index + 1,
                code: location.code,
                name: location.name,
                extractedId: validId,
                allPossibleIds: possibleIds
            };

            console.log(`选中库位${index + 1}:`, result);
            return result;
        });

        const validSelectedIds = selectedIds.filter(item => item.extractedId).map(item => item.extractedId);
        console.log('✅ 可提取的选中库位ID:', validSelectedIds);
    }

    // 显示详细的调试对话框
    const dialogContent = `
📊 库位数据统计:
• 总库位数量: ${idAnalysis.totalLocations}
• 有效ID数量: ${idAnalysis.validIds}
• 无效ID数量: ${idAnalysis.invalidIds}
• 缺失ID数量: ${idAnalysis.missingIds}

📋 选中库位情况:
• 选中数量: ${selectedLocations.value.length}
${selectedLocations.value.length > 0 ?
            selectedLocations.value.map((item, index) => {
                const validId = [item.id, item.originalData?.id, item.locationId, item.Id].find(id => id && !isNaN(parseInt(id)));
                return `• 库位${index + 1}: ${item.code} (ID: ${validId || '❌无效'})`;
            }).join('\n') : '• 当前无选中库位'
        }

🔍 详细信息请查看浏览器控制台
    `;

    proxy.$alert(dialogContent, '库位ID调试报告', {
        confirmButtonText: '知道了',
        customClass: 'debug-dialog'
    }).catch(() => {
        // 忽略用户关闭对话框的操作
    });
};

// 批量修改库位仓库外键功能
const batchUpdateWarehouseId = async () => {
    try {
        // 验证前置条件
        if (selectedLocations.value.length === 0) {
            proxy.$message.warning('请先选择要关联的库位');
            return;
        }

        if (!formData.Id) {
            proxy.$message.warning('当前仓库ID无效，请先保存仓库');
            return;
        }

        // 显示确认对话框
        const locationNames = selectedLocations.value.map(loc => loc.code || loc.name).join('、');
        const confirmMessage = `确定要将以下 ${selectedLocations.value.length} 个库位关联到当前仓库吗？\n\n库位列表：\n${locationNames}\n\n目标仓库：${formData.WarehouseName}`;

        await proxy.$confirm(confirmMessage, '批量关联库位确认', {
            confirmButtonText: '确定关联',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }).catch(() => {
            // 用户取消操作，抛出 'cancel' 让外层catch处理
            throw 'cancel';
        });

        console.log('🚀 用户确认批量关联操作');
        console.log(`📊 操作详情：将 ${selectedLocations.value.length} 个库位关联到仓库ID: ${formData.Id}`);

        // 执行批量修改
        const result = await updateLocationWarehouseIds(formData.Id);

        if (result) {
            // 移除批量关联成功消息提示
            // proxy.$message({
            //     message: `🎉 批量关联成功！已将 ${selectedLocations.value.length} 个库位关联到当前仓库`,
            //     type: 'success',
            //     duration: 5000,
            //     showClose: true
            // });
        } else {
            // 保留错误消息提示
            proxy.$message.error('批量关联失败，请查看控制台错误信息');
        }

    } catch (error) {
        if (error === 'cancel') {
            console.log('⚠️ 用户取消了批量关联操作');
            // 移除取消操作消息提示
            // proxy.$message.info('已取消批量关联操作');
        } else {
            console.error('❌ 批量关联库位失败:', error);
            // 保留错误消息提示
            proxy.$message.error(`批量关联失败: ${error.message || '未知错误'}`);
        }
    }
};

// 全选库位
const selectAllLocations = () => {
    try {
        console.log('🎯 开始全选操作...');
        console.log('📊 当前库位数量:', locationData.value.length);

        if (locationTable.value) {
            // 使用表格的全选方法
            locationTable.value.toggleAllSelection();
            console.log('✅ 已触发表格全选方法');

            // 等待一下再检查结果
            setTimeout(() => {
                console.log('📈 全选后的结果，选中数量:', selectedLocations.value.length);
                if (selectedLocations.value.length > 0) {
                    // 移除全选成功消息提示
                    // proxy.$message.success(`成功全选 ${selectedLocations.value.length} 个库位`);
                } else {
                    console.warn('⚠️ 表格全选方法没有效果，尝试手动全选');
                    // 手动全选
                    selectedLocations.value = [...locationData.value];
                    // 移除手动全选成功消息提示
                    // proxy.$message.success(`手动全选 ${locationData.value.length} 个库位`);
                }
            }, 100);
        } else {
            console.warn('⚠️ 表格引用不存在，使用手动全选');
            // 备选方案：手动设置选中状态
            selectedLocations.value = [...locationData.value];
            console.log('🎯 手动全选完成，数量:', selectedLocations.value.length);
            // 移除手动全选成功消息提示
            // proxy.$message.success(`手动全选 ${locationData.value.length} 个库位`);
        }
    } catch (error) {
        console.error('❌ 全选库位失败:', error);
        proxy.$message.error('全选操作失败: ' + error.message);
    }
};

// 清空选择
const clearAllSelections = () => {
    try {
        console.log('🗑️ 开始清空选择...');

        if (locationTable.value) {
            locationTable.value.clearSelection();
            console.log('✅ 已触发表格清空方法');

            // 等待一下再检查结果
            setTimeout(() => {
                console.log('📉 清空后的结果，选中数量:', selectedLocations.value.length);
                if (selectedLocations.value.length === 0) {
                    // 移除清空成功消息提示
                    // proxy.$message.success('已清空库位选择');
                } else {
                    console.warn('⚠️ 表格清空方法没有效果，尝试手动清空');
                    selectedLocations.value = [];
                    // 移除手动清空成功消息提示
                    // proxy.$message.success('手动清空库位选择');
                }
            }, 100);
        } else {
            console.warn('⚠️ 表格引用不存在，使用手动清空');
            // 备选方案：手动清空
            selectedLocations.value = [];
            console.log('🗑️ 手动清空完成');
            // 移除手动清空成功消息提示
            // proxy.$message.success('手动清空库位选择');
        }
    } catch (error) {
        console.error('❌ 清空选择失败:', error);
        proxy.$message.error('清空选择失败: ' + error.message);
    }
};

// 构建部门树形结构
const buildDepartmentTree = (departments) => {
    // 创建一个映射表，用于快速查找部门
    const deptMap = {};
    departments.forEach(dept => {
        deptMap[dept.value] = { ...dept, children: [] };
    });

    // 构建树形结构
    const tree = [];
    departments.forEach(dept => {
        const parentId = dept.parentId;
        // 如果是根节点或父节点不存在，则添加到根节点
        if (!parentId || parentId === '0' || parentId === 0 || parentId === '(Null)' || parentId === '(null)' || !deptMap[parentId]) {
            tree.push(deptMap[dept.value]);
        } else {
            // 否则添加到父节点的children中
            if (deptMap[parentId]) {
                deptMap[parentId].children.push(deptMap[dept.value]);
            }
        }
    });

    // 递归清理空的children数组
    const cleanEmptyChildren = (nodes) => {
        if (!nodes) return [];
        return nodes.map(node => {
            if (node.children && node.children.length === 0) {
                const { children, ...rest } = node;
                return rest;
            }
            if (node.children && node.children.length > 0) {
                node.children = cleanEmptyChildren(node.children);
            }
            return node;
        });
    };

    return cleanEmptyChildren(tree);
};

// 根据部门ID获取部门名称
const getDepartmentName = (deptId) => {
    if (!deptId) return '';
    return departmentMap.value[deptId] || deptId;
};

// 根据仓库ID获取仓库名称
const getWarehouseName = (warehouseId) => {
    if (!warehouseId || warehouseId === 0) {
        return '未分配';
    }
    // 如果是当前仓库，返回当前仓库名称
    if (warehouseId === formData.Id) {
        return formData.WarehouseName || `仓库${warehouseId}`;
    }
    // 否则返回仓库ID（后续可以扩展为从API获取仓库名称）
    return `仓库${warehouseId}`;
};

// 处理部门选择变化
const handleDeptChange = (value) => {
    console.log('选择的部门ID:', value);
    formData.deptId = value;
    console.log('选择的部门名称:', getDepartmentName(value));
};

// 处理用户选择变化
const handleUserChange = (value) => {
    console.log('选择的用户ID:', value, '类型:', typeof value);
    // 确保userId是数字类型
    formData.userId = parseInt(value || 0);

    // 查找选中的用户，获取更多信息（如果需要）
    const selectedUser = userOptions.value.find(user => user.value === formData.userId);
    if (selectedUser) {
        console.log('选中的用户:', selectedUser.label);
    }
};

// 分页变化
const handleCurrentChange = (page) => {
    currentPage.value = page;
    queryParams.page = page - 1; // API是从0开始计数
    loadStorageLocations();
};

// 处理页码大小变化
const handlePageSizeChange = (size) => {
    pageSize.value = size;
    queryParams.rows = size;
    currentPage.value = 1;
    queryParams.page = 0;
    loadStorageLocations();
};

// 加载库位数据
const loadStorageLocations = async () => {
    try {
        // 更新查询参数
        queryParams.page = currentPage.value - 1;
        queryParams.rows = pageSize.value;

        // 如果是编辑模式，添加仓库ID过滤条件
        if (route.query.id && formData.Id) {
            queryParams.wheres = `warehouseId=${formData.Id}`;
            console.log('添加仓库ID过滤条件:', queryParams.wheres);
        } else {
            // 新增模式或没有仓库ID时，清空过滤条件以显示所有未分配的库位
            queryParams.wheres = 'warehouseId=0 OR warehouseId IS NULL';
            console.log('显示未分配的库位');
        }

        // 调用API获取库位数据 - 使用正确的API路径
        const response = await proxy.http.post('/api/storagelocationmodel/GetPageData', queryParams);

        if (response && response.rows) {
            // 转换数据格式以适应表格 - 根据API返回的实际字段进行映射
            locationData.value = response.rows.map((item, index) => {
                // 检查返回的数据结构
                console.log('API返回的库位数据项:', item);
                console.log('库位数据项的所有属性:', Object.keys(item));

                // 保存原始数据的副本，避免引用问题
                const originalData = JSON.parse(JSON.stringify(item));

                // 提取库位ID - 尝试多种可能的字段名
                const locationId = item.id || item.Id || item.locationId || item.LocationId || item.pkId || item.key || 0;
                console.log(`库位 ${item.locationCode || '未知'} 的ID提取结果: ${locationId} (来源字段: ${item.id ? 'id' :
                    item.Id ? 'Id' :
                        item.locationId ? 'locationId' :
                            item.LocationId ? 'LocationId' :
                                item.pkId ? 'pkId' :
                                    item.key ? 'key' : '未找到'
                    })`);

                const mappedData = {
                    index: (currentPage.value - 1) * pageSize.value + index + 1,
                    // 根据API响应中的实际字段名称进行映射
                    code: item.locationCode || '',
                    name: item.locationName || '',
                    capacity: item.locationCapacity || 0,
                    warehouseName: getWarehouseName(item.warehouseId), // 显示仓库名称
                    manager: item.userId || '',
                    order: item.locationSort || 0,
                    status: item.locationState || 0,
                    remark: item.remark || '',
                    // 🎯 关键：确保ID字段正确映射
                    id: locationId,  // 使用提取到的ID
                    warehouseId: item.warehouseId || 0,  // 添加仓库ID字段
                    // 保留原始数据，以便更新时使用
                    originalData: originalData
                };

                console.log(`映射后的库位数据:`, {
                    code: mappedData.code,
                    name: mappedData.name,
                    id: mappedData.id,
                    warehouseId: mappedData.warehouseId,
                    originalDataId: originalData.id || originalData.Id || originalData.locationId || '未找到'
                });

                return mappedData;
            });

            // 更新总数
            totalLocations.value = response.total || 0;
            console.log('加载库位数据成功，总数:', totalLocations.value);

            // 验证库位数据的ID字段
            console.log('🔍 验证加载的库位数据ID字段:');
            const validIdCount = locationData.value.filter(item => item.id && !isNaN(parseInt(item.id))).length;
            const invalidIdCount = locationData.value.length - validIdCount;

            console.log(`  - 总库位数量: ${locationData.value.length}`);
            console.log(`  - 有效ID数量: ${validIdCount}`);
            console.log(`  - 无效ID数量: ${invalidIdCount}`);

            if (invalidIdCount > 0) {
                console.warn('⚠️ 存在ID无效的库位数据，可能影响库位关联功能');
                locationData.value.forEach((item, index) => {
                    if (!item.id || isNaN(parseInt(item.id))) {
                        console.warn(`  - 库位${index + 1}: ${item.code} ID无效: ${item.id}`);
                    }
                });
            } else {
                console.log('✅ 所有库位的ID字段都正常');
            }
        } else {
            locationData.value = [];
            totalLocations.value = 0;
            console.log('API返回数据为空或格式不正确');
        }
    } catch (error) {
        console.error('加载库位数据失败', error);
        proxy.$message.error('加载库位数据失败');
        locationData.value = [];
        totalLocations.value = 0;
    }
};

// 添加库位
const addLocation = () => {
    // 这里可以实现添加库位的逻辑，例如打开一个对话框
    proxy.$message.info('添加库位功能待实现');
};

// 删除选中库位
const deleteLocation = async () => {
    if (selectedLocations.value.length === 0) {
        proxy.$message.warning('请选择要删除的库位');
        return;
    }

    try {
        // 确认删除
        await proxy.$confirm('确定要删除选中的库位吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(() => {
            // 用户取消操作，抛出 'cancel' 让外层catch处理
            throw 'cancel';
        });

        // 获取选中项的ID
        const ids = selectedLocations.value.map(item => item.id).join(',');

        // 调用删除API
        const response = await proxy.http.post('/api/storagelocationmodel/delete', { ids });

        if (response && response.status) {
            // 移除删除成功消息提示
            // proxy.$message.success('删除成功');
            loadStorageLocations(); // 重新加载数据
        } else {
            // 保留删除失败消息提示
            proxy.$message.error(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除库位失败', error);
        if (error !== 'cancel') {
            proxy.$message.error('删除库位失败');
        }
    }
};

// 删除单个库位
const deleteLocationItem = async (row) => {
    try {
        // 确认删除
        await proxy.$confirm('确定要删除该库位吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(() => {
            // 用户取消操作，抛出 'cancel' 让外层catch处理
            throw 'cancel';
        });

        // 调用删除API
        const response = await proxy.http.post('/api/storagelocationmodel/delete', { ids: row.id });

        if (response && response.status) {
            // 移除删除成功消息提示
            // proxy.$message.success('删除成功');
            loadStorageLocations(); // 重新加载数据
        } else {
            // 保留删除失败消息提示
            proxy.$message.error(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除库位失败', error);
        if (error !== 'cancel') {
            proxy.$message.error('删除库位失败');
        }
    }
};

// 编辑库位
const editLocation = (row) => {
    // 这里可以实现编辑库位的逻辑，例如打开一个对话框
    proxy.$message.info('编辑库位功能待实现');
};

// 导入库位
const importLocation = () => {
    proxy.$message.info('导入库位功能待实现');
};

// 导出库位
const exportLocation = () => {
    proxy.$message.info('导出库位功能待实现');
};

// 保存仓库
const saveWarehouse = async () => {
    try {
        // 表单验证
        if (!formData.WarehouseCode) {
            proxy.$message.warning('请输入仓库编号');
            return;
        }
        if (!formData.WarehouseName) {
            proxy.$message.warning('请输入仓库名称');
            return;
        }
        // 验证仓库容量是否为数字
        if (formData.Capacity && isNaN(Number(formData.Capacity))) {
            proxy.$message.warning('仓库容量必须为数字');
            return;
        }
        // 验证部门ID
        if (!formData.deptId) {
            proxy.$message.warning('请选择库管部门');
            return;
        }
        // 验证仓库主管
        if (!formData.userId) {
            proxy.$message.warning('请选择仓库主管');
            return;
        }

        // 准备提交的数据对象，根据API文档格式
        let submitData;

        if (!route.query.id) {
            // 新增操作 - 按照API文档格式
            submitData = {
                "mainData": {
                    "WarehouseCode": formData.WarehouseCode,
                    "WarehouseName": formData.WarehouseName,
                    "Capacity": parseInt(formData.Capacity) || 1000,
                    "Warehouseaddr": formData.Warehouseaddr,
                    "deptId": formData.deptId,
                    "deptName": getDepartmentName(formData.deptId), // 添加部门名称
                    "userId": formData.userId,
                    "status": formData.status || 1
                },
                "detailData": [],
                "delKeys": []
            };

            // 如果有备注，添加到mainData中
            if (formData.WarehouseDesc) {
                submitData.mainData.WarehouseDesc = formData.WarehouseDesc;
            }
        } else {
            // 编辑操作 - 使用原始格式
            submitData = {
                Id: formData.Id,
                WarehouseCode: formData.WarehouseCode,
                WarehouseName: formData.WarehouseName,
                Capacity: formData.Capacity,
                Warehouseaddr: formData.Warehouseaddr,
                deptId: formData.deptId,
                deptName: getDepartmentName(formData.deptId), // 添加部门名称
                userId: formData.userId,
                status: formData.status,
                WarehouseDesc: formData.WarehouseDesc,
                IsDel: formData.IsDel,
                Creator: formData.Creator,
                CreateDate: formData.CreateDate,
                Modifier: formData.Modifier,
                ModifyDate: formData.ModifyDate,
                CreateID: formData.CreateID,
                ModifyID: formData.ModifyID
            };
        }

        // 获取用户信息
        const userInfo = proxy.$store.getters.getUserInfo();

        // 只有编辑操作需要设置修改人信息
        // 新增操作的创建人信息由后端处理（根据API文档说明）
        if (route.query.id) {
            // 如果是编辑，设置修改人信息
            if (userInfo) {
                submitData.ModifyID = userInfo.userId;
                submitData.Modifier = userInfo.userName;
                // 设置修改时间为当前时间
                submitData.ModifyDate = new Date().toISOString();
            }
        }

        const apiPath = !route.query.id ? '/api/warehousemodel/Add' : '/api/warehousemodel/save';
        console.log('提交的数据:', submitData);
        console.log(`API请求路径: ${apiPath}`);
        console.log('请求方法: POST');

        // 根据是否有ID确定是新增还是编辑
        let url;
        const baseURL = 'http://localhost:8080';

        if (!route.query.id) {
            // 新增操作 - 使用Add接口
            url = `${baseURL}/api/warehousemodel/Add`;
            console.log('执行添加操作，API路径:', url);
        } else {
            // 编辑操作 - 使用save接口
            url = `${baseURL}/api/warehousemodel/save`;
            console.log('执行编辑操作，API路径:', url);
        }

        console.log('完整请求URL:', url);

        // 获取授权令牌
        const token = proxy.$store.getters.getToken();

        const response = await axios.post(url, JSON.stringify(submitData), {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Authorization': token
            }
        });
        // axios响应包含data属性，其中包含实际的响应数据
        console.log('API响应状态码:', response.status);
        console.log('API响应数据:', response.data);

        // 检查HTTP状态码是否成功
        if (response.status >= 200 && response.status < 300) {
            // 检查业务逻辑状态 - 根据API文档，成功响应格式为 { "status": true, "message": "添加成功", "data": null, "responseType": 0 }
            if (response.data && response.data.status) {
                // 添加仓库保存成功消息提示
                const successMsg = !route.query.id ? '仓库添加成功' : '仓库保存成功';
                proxy.$message.success(response.data.message || successMsg);

                // 检查是否有选中的库位需要关联
                console.log('🔍 检查选中的库位数量:', selectedLocations.value.length);
                console.log('📋 选中的库位详情:', selectedLocations.value);

                if (selectedLocations.value.length > 0) {
                    let warehouseId;

                    if (!route.query.id) {
                        // 新增操作 - 从响应中获取新创建的仓库ID
                        console.log('🔍 深度分析API响应结构以获取新仓库ID:');
                        console.log('  - 完整响应:', JSON.stringify(response.data, null, 2));

                        let responseData = response.data.data;
                        console.log('  - response.data.data类型:', typeof responseData);

                        if (responseData && typeof responseData === 'object') {
                            console.log('  - response.data.data所有属性:', Object.keys(responseData));

                            // 检查常见的ID字段名
                            const possibleIdFields = ['Id', 'id', 'ID', 'warehouseId', 'WarehouseId', 'pkId', 'key'];
                            console.log('  - 检查可能的ID字段:');
                            possibleIdFields.forEach(field => {
                                console.log(`    - ${field}:`, responseData[field]);
                            });
                        }

                        // 尝试多种方式获取仓库ID - 更全面的检查
                        warehouseId = response.data.data?.Id ||
                            response.data.data?.id ||
                            response.data.data?.ID ||
                            response.data.data?.warehouseId ||
                            response.data.data?.WarehouseId ||
                            response.data.data?.pkId ||
                            response.data.data?.key ||
                            response.data.Id ||
                            response.data.id ||
                            response.data.ID ||
                            response.data.warehouseId;

                        console.log('📋 首次提取到的仓库ID:', warehouseId, '类型:', typeof warehouseId);

                        // 如果还是没有找到，尝试从字符串中解析ID
                        if (!warehouseId && typeof response.data.data === 'string') {
                            console.log('🔄 响应数据是字符串，尝试解析ID');
                            const idMatch = response.data.data.match(/\d+/);
                            if (idMatch) {
                                warehouseId = idMatch[0];
                                console.log('📋 从字符串中解析出ID:', warehouseId);
                            }
                        }

                        // 如果还是没有找到，尝试使用最新创建的仓库信息
                        if (!warehouseId) {
                            console.log('🔄 尝试使用刚提交的仓库编号查询最新仓库ID');
                            try {
                                warehouseId = await getLatestWarehouseId(formData.WarehouseCode);
                                console.log('📋 通过查询获取的仓库ID:', warehouseId);
                            } catch (queryError) {
                                console.error('❌ 查询最新仓库ID失败:', queryError);
                            }
                        }

                        if (!warehouseId) {
                            console.error('❌ 所有方法都无法获取新创建的仓库ID');
                            console.error('🔍 完整API响应:', JSON.stringify(response.data, null, 2));
                            // 移除包含"仓库创建成功"的警告消息
                            // proxy.$message.warning('仓库创建成功，但无法获取仓库ID关联库位，请手动关联');
                            router.push('/warehousemodel');
                            return;
                        }

                        // 确保warehouseId是数字类型
                        const numericWarehouseId = parseInt(warehouseId);
                        if (isNaN(numericWarehouseId)) {
                            console.error('❌ 获取的仓库ID不是有效数字:', warehouseId);
                            // 移除包含"仓库创建成功"的警告消息
                            // proxy.$message.warning('仓库创建成功，但仓库ID格式异常，请手动关联库位');
                            router.push('/warehousemodel');
                            return;
                        }

                        warehouseId = numericWarehouseId;

                        console.log('✅ 新增仓库 - 成功获取仓库ID:', warehouseId);
                    } else {
                        // 编辑操作 - 使用当前仓库ID
                        warehouseId = parseInt(formData.Id);
                        console.log('✅ 编辑仓库 - 使用当前仓库ID:', warehouseId);
                    }

                    console.log(`🎯 准备更新${selectedLocations.value.length}个选中库位的warehouseId字段为: ${warehouseId}`);

                    try {
                        const updateResult = await updateLocationWarehouseIds(warehouseId);
                        if (updateResult) {
                            // 移除库位关联成功消息提示
                            // const locationNames = selectedLocations.value.map(loc => loc.code || loc.name).join('、');
                            // const successMessage = `🎉 仓库保存成功！\n已将${selectedLocations.value.length}个库位关联到当前仓库:\n${locationNames}`;
                            // proxy.$message({
                            //     message: successMessage,
                            //     type: 'success',
                            //     duration: 5000,
                            //     showClose: true
                            // });

                            console.log('✅ 库位关联完成总结:');
                            console.log(`  - 仓库ID: ${warehouseId}`);
                            console.log(`  - 关联库位数量: ${selectedLocations.value.length}`);
                            const locationNames = selectedLocations.value.map(loc => loc.code || loc.name).join('、');
                            console.log(`  - 关联库位列表: ${locationNames}`);
                        }
                    } catch (error) {
                        console.error('❌ 更新库位仓库ID失败:', error);
                        // 移除包含"仓库保存成功"的警告消息
                        // proxy.$message.warning(`仓库保存成功，但库位关联失败: ${error.message || '未知错误'}，请手动关联`);
                    }
                } else {
                    // 没有选中库位的情况
                    console.log('⚠️ 没有选中任何库位，跳过库位关联');
                    // 移除保存成功消息提示
                    // proxy.$message.info('仓库保存成功！如需关联库位，请先选中库位后再保存');
                }

                router.push('/warehousemodel');
            } else {
                // 业务逻辑错误
                const errorMsg = response.data?.message || (!route.query.id ? '添加失败，请检查数据' : '保存失败，请检查数据');
                proxy.$message.error(errorMsg);
                console.error('业务逻辑错误:', errorMsg);
            }
        } else {
            // HTTP错误
            proxy.$message.error(`请求错误: ${response.status}`);
        }
    } catch (error) {
        console.error('保存仓库失败', error);

        // 更详细的错误处理
        if (error.response) {
            // 服务器返回了错误状态码
            console.error('错误状态码:', error.response.status);
            console.error('错误数据:', error.response.data);
            proxy.$message.error(`保存失败: ${error.response.status} - ${error.response.data?.message || '服务器错误'}`);
        } else if (error.request) {
            // 请求发送成功，但没有收到响应
            console.error('未收到响应:', error.request);
            proxy.$message.error('保存失败: 服务器无响应');
        } else {
            // 请求设置时发生错误
            console.error('请求错误:', error.message);
            proxy.$message.error(`保存失败: ${error.message}`);
        }
    }
};

// 批量修改库位仓库外键 - 使用专用的BatchUpdateWarehouseId接口
const updateLocationWarehouseIds = async (warehouseId) => {
    if (!warehouseId || selectedLocations.value.length === 0) {
        console.warn('⚠️ 批量修改跳过：warehouseId为空或没有选中库位');
        return false;
    }

    try {
        console.log('🚀 ===== 开始批量修改库位仓库外键 =====');
        console.log(`📊 操作概览：`);
        console.log(`  - 目标仓库ID: ${warehouseId}`);
        console.log(`  - 选中库位数量: ${selectedLocations.value.length}`);
        console.log(`  - API接口: /api/storagelocationmodel/BatchUpdateWarehouseId`);

        // 提取选中库位的ID数组 - 增强库位ID提取逻辑
        console.log('🔍 开始提取选中库位的ID...');
        console.log('📋 选中库位的原始数据:', selectedLocations.value);

        const locationIds = selectedLocations.value.map((location, index) => {
            console.log(`🔍 正在处理第${index + 1}个库位:`, location);

            // 尝试多种可能的ID字段
            const possibleIds = [
                location.id,
                location.originalData?.id,
                location.locationId,
                location.Id,  // 大写ID
                location.originalData?.Id,  // 大写ID
                location.originalData?.locationId,  // 原始数据中的locationId
                location.pkId,  // 主键ID
                location.originalData?.pkId,  // 原始数据中的主键ID
                location.key,   // 键值
                location.originalData?.key   // 原始数据中的键值
            ];

            console.log(`📊 第${index + 1}个库位的候选ID字段:`, {
                'location.id': location.id,
                'location.originalData?.id': location.originalData?.id,
                'location.locationId': location.locationId,
                'location.Id': location.Id,
                'location.originalData?.Id': location.originalData?.Id,
                'location.originalData?.locationId': location.originalData?.locationId,
                'location.pkId': location.pkId,
                'location.originalData?.pkId': location.originalData?.pkId,
                'location.key': location.key,
                'location.originalData?.key': location.originalData?.key
            });

            // 找到第一个有效的ID
            for (const id of possibleIds) {
                if (id !== undefined && id !== null && id !== '' && !isNaN(parseInt(id))) {
                    console.log(`✅ 第${index + 1}个库位找到有效ID: ${id} (类型: ${typeof id})`);
                    return parseInt(id);
                }
            }

            console.error(`❌ 第${index + 1}个库位没有找到有效ID`);
            console.error(`❌ 库位完整数据:`, JSON.stringify(location, null, 2));
            return null;
        }).filter(id => id !== null && !isNaN(id)); // 过滤掉无效的ID

        console.log('📊 ID提取结果:');
        console.log(`  - 选中库位总数: ${selectedLocations.value.length}`);
        console.log(`  - 提取到的有效ID数量: ${locationIds.length}`);
        console.log(`  - 有效ID列表: [${locationIds.join(', ')}]`);

        if (locationIds.length === 0) {
            console.error('❌ 没有找到任何有效的库位ID');
            console.error('🔍 调试信息:');
            console.error('  - 选中库位数量:', selectedLocations.value.length);
            console.error('  - 选中库位详情:', selectedLocations.value);

            // 详细分析每个选中的库位
            selectedLocations.value.forEach((location, index) => {
                console.error(`  - 库位${index + 1}完整数据:`, location);
                console.error(`  - 库位${index + 1}所有属性:`, Object.keys(location));
                if (location.originalData) {
                    console.error(`  - 库位${index + 1}原始数据属性:`, Object.keys(location.originalData));
                }
            });

            proxy.$message.error('选中的库位数据异常，无法获取有效的库位ID。请检查库位数据是否正确加载。');
            return false;
        }

        if (locationIds.length !== selectedLocations.value.length) {
            console.warn(`⚠️ 部分库位ID提取失败: ${selectedLocations.value.length - locationIds.length}个库位没有有效ID`);
            proxy.$message.warning(`部分库位ID无效，将只更新${locationIds.length}个库位的仓库关联`);
        }

        // 显示将要修改的库位详情
        console.log('📝 将要修改的库位列表:');
        selectedLocations.value.forEach((location, index) => {
            const locationId = location.id || location.originalData?.id || location.locationId;
            console.log(`  ${index + 1}. 库位ID: ${locationId}`);
            console.log(`     - 编号: ${location.code}`);
            console.log(`     - 名称: ${location.name}`);
            console.log(`     - 当前warehouseId: ${location.warehouseId || '未设置'}`);
            console.log(`     - 新warehouseId: ${warehouseId} ⭐`);
        });

        // 构建专用API的请求数据 - 根据API文档格式
        const requestData = {
            "ids": locationIds,        // 库位ID数组
            "warehouseId": parseInt(warehouseId)  // 目标仓库ID
        };

        console.log('🔧 ===== 批量修改API请求数据构建完成 =====');
        console.log('📊 请求数据统计:');
        console.log(`  - 库位ID数组长度: ${locationIds.length}`);
        console.log(`  - 库位ID列表: [${locationIds.join(', ')}]`);
        console.log(`  - 目标仓库ID: ${warehouseId}`);
        console.log('📋 完整请求数据:', JSON.stringify(requestData, null, 2));

        // 首先尝试使用proxy.http调用专用API
        try {
            console.log('🚀 开始使用proxy.http调用专用批量更新接口...');
            console.log('📡 API路径: /api/storagelocationmodel/BatchUpdateWarehouseId');

            const response = await proxy.http.post('/api/storagelocationmodel/BatchUpdateWarehouseId', requestData);

            console.log('📥 API响应原始数据:', response);
            console.log('📊 响应分析:');
            console.log('  - 响应类型:', typeof response);
            console.log('  - 是否有status字段:', 'status' in response);
            console.log('  - status值:', response?.status);
            console.log('  - status类型:', typeof response?.status);
            console.log('  - 是否有message字段:', 'message' in response);
            console.log('  - message值:', response?.message);
            console.log('  - 是否有code字段:', 'code' in response);
            console.log('  - code值:', response?.code);
            console.log('  - 所有属性:', Object.keys(response || {}));

            // 判断API调用是否成功
            let isSuccess = false;
            let successReason = '';

            if (response) {
                if (response.status === true) {
                    isSuccess = true;
                    successReason = 'status === true';
                } else if (response.status === 'true') {
                    isSuccess = true;
                    successReason = 'status === "true"';
                } else if (response.status === 1) {
                    isSuccess = true;
                    successReason = 'status === 1';
                } else if (response.code === 200) {
                    isSuccess = true;
                    successReason = 'code === 200';
                } else if (response.status === 200) {
                    isSuccess = true;
                    successReason = 'status === 200';
                } else if (response.success === true) {
                    isSuccess = true;
                    successReason = 'success === true';
                } else if (!response.status && !response.code && !response.error && response.message) {
                    // 如果有message但没有明确的错误标识，可能也是成功的
                    isSuccess = true;
                    successReason = '有消息但无错误标识，判定为成功';
                }
            }

            if (isSuccess) {
                console.log('🎉 ===== 批量修改库位仓库外键成功 =====');
                console.log(`✅ API调用成功原因: ${successReason}`);
                console.log(`📊 成功修改统计:`);
                console.log(`  - 修改库位数量: ${locationIds.length}`);
                console.log(`  - 库位ID列表: [${locationIds.join(', ')}]`);
                console.log(`  - 目标仓库ID: ${warehouseId}`);
                console.log(`  - API响应消息: ${response.message || '无消息'}`);

                try {
                    // 重新加载库位数据以验证批量修改结果
                    console.log('🔄 重新加载库位数据以验证批量修改结果...');
                    await loadStorageLocations();
                    console.log('✅ 库位数据重新加载成功！');
                    console.log('📋 请检查表格中"所属仓库"列是否显示正确的仓库名称');

                    // 清空选择状态
                    selectedLocations.value = [];
                    console.log('🧹 已清空库位选择状态');

                } catch (reloadError) {
                    console.warn('⚠️ 库位数据重新加载失败:', reloadError);
                }

                console.log('🏁 批量修改库位仓库外键操作完成');
                return true; // 成功返回
            } else {
                // 详细记录响应信息用于调试
                console.error('❌ 批量更新库位判定为失败');
                console.error('🔍 失败原因分析:');
                console.error('  - response存在:', !!response);
                console.error('  - status值:', response?.status);
                console.error('  - code值:', response?.code);
                console.error('  - success值:', response?.success);
                console.error('  - error值:', response?.error);
                console.error('📄 完整响应数据:', JSON.stringify(response, null, 2));

                const errorMsg = response?.message || response?.msg || response?.error || '更新失败，API响应格式不符合预期';
                throw new Error(errorMsg);
            }
        } catch (error) {
            console.error('proxy.http更新失败，尝试axios备选方案:', error);

            // 备选方案：使用axios直接调用专用API
            try {
                const baseURL = 'http://localhost:8080';
                const url = `${baseURL}/api/storagelocationmodel/BatchUpdateWarehouseId`;
                const token = proxy.$store.getters.getToken();

                console.log('🔄 使用axios备选方案调用专用批量更新接口...');
                console.log('📡 完整请求URL:', url);

                const response = await axios.post(url, JSON.stringify(requestData), {
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8',
                        'Authorization': token
                    }
                });

                console.log('📥 axios批量更新库位响应:', response.data);
                console.log('📊 axios响应状态码:', response.status);
                console.log('📊 axios响应数据类型:', typeof response.data);

                // 检查HTTP状态和业务状态
                if (response.status >= 200 && response.status < 300) {
                    if (response.data && (
                        response.data.status === true ||
                        response.data.status === 'true' ||
                        response.data.code === 200 ||
                        response.data.success === true
                    )) {
                        console.log(`✅ axios成功更新${locationIds.length}个库位的仓库ID`);
                        console.log(`📋 API响应消息: ${response.data.message || '无消息'}`);

                        // 重新加载库位数据
                        try {
                            await loadStorageLocations();
                            console.log('📋 库位数据重新加载成功');

                            // 清空选择状态
                            selectedLocations.value = [];
                            console.log('🧹 已清空库位选择状态');
                        } catch (reloadError) {
                            console.warn('⚠️ 库位数据重新加载失败:', reloadError);
                        }

                        return true; // 成功返回
                    } else {
                        console.error('❌ axios业务逻辑判定为失败');
                        console.error('📄 axios完整响应数据:', JSON.stringify(response.data, null, 2));
                        const errorMsg = response.data?.message || response.data?.msg || '更新失败，请检查数据';
                        throw new Error(errorMsg);
                    }
                } else {
                    throw new Error(`HTTP错误: ${response.status}`);
                }
            } catch (axiosError) {
                console.error('❌ axios备选方案也失败了:', axiosError);

                // 提取详细的错误信息
                let errorMessage = '未知错误';
                if (axiosError.response) {
                    errorMessage = `服务器错误 ${axiosError.response.status}: ${axiosError.response.data?.message || axiosError.response.statusText}`;
                    console.error('📄 axios错误响应数据:', axiosError.response.data);
                } else if (axiosError.request) {
                    errorMessage = '服务器无响应';
                } else {
                    errorMessage = axiosError.message;
                }

                throw new Error(`专用API调用失败: ${errorMessage}`);
            }
        }
    } catch (error) {
        console.error('🚨 ===== 批量修改库位仓库外键失败 =====');
        console.error('❌ 错误详情:', error.message);
        console.error('📊 失败统计:');
        console.error(`  - 目标仓库ID: ${warehouseId}`);
        console.error(`  - 尝试修改库位数量: ${selectedLocations.value.length}`);
        console.error(`  - 失败原因: ${error.message}`);

        // 抛出错误供上层处理
        throw error;
    }
};

// 通过仓库编号查询最新仓库ID（备用方案）
const getLatestWarehouseId = async (warehouseCode) => {
    try {
        console.log('🔍 通过仓库编号查询最新仓库ID，编号:', warehouseCode);

        // 调用仓库列表API
        const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
            page: 0,
            rows: 10, // 获取最近的10个仓库
            sort: "Id desc", // 按ID降序排列，获取最新的
            order: "",
            wheres: warehouseCode ? `WarehouseCode='${warehouseCode}'` : "",
            tableName: "warehousemodel",
            filter: []
        });

        console.log('📋 查询仓库响应:', response);

        if (response && response.rows && response.rows.length > 0) {
            // 如果指定了仓库编号，查找匹配的仓库
            if (warehouseCode) {
                const matchedWarehouse = response.rows.find(warehouse =>
                    warehouse.WarehouseCode === warehouseCode ||
                    warehouse.warehouseCode === warehouseCode ||
                    warehouse.code === warehouseCode
                );

                if (matchedWarehouse) {
                    const foundId = matchedWarehouse.Id || matchedWarehouse.id || matchedWarehouse.warehouseId;
                    console.log('✅ 找到匹配的仓库:', matchedWarehouse);
                    console.log('📋 提取的仓库ID:', foundId);
                    return parseInt(foundId);
                }
            }

            // 如果没有指定编号或没有找到匹配的，使用最新的仓库
            const latestWarehouse = response.rows[0]; // 第一个应该是最新的
            if (latestWarehouse) {
                const latestId = latestWarehouse.Id || latestWarehouse.id || latestWarehouse.warehouseId;
                console.log('📋 使用最新仓库的ID:', latestId, '仓库编号:', latestWarehouse.WarehouseCode || latestWarehouse.warehouseCode);
                return parseInt(latestId);
            }
        }

        console.error('❌ 无法通过查询获取仓库ID');
        return null;
    } catch (error) {
        console.error('❌ 查询仓库ID时发生错误:', error);
        return null;
    }
};

// 取消编辑
const cancelEdit = () => {
    router.push('/warehousemodel');
};
</script>

<style lang="less" scoped>
.warehouse-detail-container {
    padding: 20px;
    background-color: #fff;

    .info-section,
    .location-section {
        margin-bottom: 20px;
        border: 1px solid #ebeef5;
        border-radius: 4px;

        .section-title {
            padding: 10px 15px;
            font-size: 16px;
            font-weight: bold;
            background-color: #f5f7fa;
            border-bottom: 1px solid #ebeef5;
        }

        .form-content {
            padding: 20px;
        }

        .location-tips {
            padding: 10px 15px;
            background-color: #f0f9ff;
        }

        .table-actions {
            padding: 10px 15px;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;

            .action-group {
                display: flex;
                gap: 8px;
            }

            .selection-group {
                display: flex;
                align-items: center;
                gap: 8px;
                flex-wrap: wrap;
            }
        }

        .table-content {
            padding: 0 15px;
        }

        .pagination {
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .page-size-selector {
                display: flex;
                align-items: center;
                gap: 10px;
            }
        }
    }

    .form-actions {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 20px;
    }
}

// 调试对话框样式
:deep(.debug-dialog) {
    .el-message-box__content {
        white-space: pre-line;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        max-height: 400px;
        overflow-y: auto;
    }
}
</style>
